from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadSignature
from django.conf import settings

from users.models import User


def generic_active_url(user_id, email):
    """加密url"""
    #  创建加密对象
    serializer = Serializer(settings.SECRET_KEY, 3600)

    #  组织数据
    data = {
        'user_id': user_id,
        'email': email
    }

    #  加密处理
    token = serializer.dumps(data)
    return 'http://www.meiduo.site:8080/success_verify_email.html?token=' + token.decode()


def get_active_user(token):
    """解密"""
    #  创建加密对象
    serializer = Serializer(settings.SECRET_KEY, 3600)

    #  解密
    try:
        result = serializer.loads(token)
    except BadSignature:
        return None
    else:
        #  获取id 和　邮箱
        id = result.get('user_id')
        email = result.get('email')
        #  根据id 去获取对象
        try:
            user = User.objects.get(id=id, email=email)
        except User.DoesNoTExist:
            return None
        else:
            return user
